package com.rpc.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc
 */
public class NIOClient {

  private Selector selector;

  private final static int PORT = 8888;

  private final static String HOST = "localhost";

  private SocketChannel socketChannel;

  private String userName;


  public NIOClient() throws IOException {
    //创建注册集
    selector = Selector.open();
    //连接服务器
    socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
    //设置非阻塞
    socketChannel.configureBlocking(false);
    //注册到注册集
    socketChannel.register(selector, SelectionKey.OP_READ);
    userName = socketChannel.getRemoteAddress().toString();

    System.out.println(userName+"ok......"
        + "");

  }

  /**
   * @describe 发送消息到服务器
   * @author 何章怀晓 hezhanghuaixiao
   * @date 2022/2/28  12:22
   * @other
   */
  public void sentMsgToServer(String msg) {

    try {
      socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  public void readMsgByServer() {
    try {
      int read = selector.select();

      while (true) {
        if (read > 0) {
          Set<SelectionKey> selectionKeys = selector.selectedKeys();

          Iterator<SelectionKey> iterator = selectionKeys.iterator();

          while (iterator.hasNext()) {
            SelectionKey key = iterator.next();
            if (key.isReadable()) {
              SocketChannel channel = (SocketChannel) key.channel();
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              channel.read(buffer);
              String msg = new String(buffer.array());
              System.out.println(userName + "读取服务器新信息" + msg);
            }
          }

          iterator.remove();
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws IOException {
    NIOClient nioClient = new NIOClient();

    new Thread() {
      @Override
      public void run() {
        while (true) {
          nioClient.readMsgByServer();
          try {
            //每隔3S读取一次channel
            Thread.sleep(3000);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }.start();
    //客户端发送数据
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
      String s = scanner.nextLine();
      nioClient.sentMsgToServer(s);
    }
  }

}
